import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {CodeParam, UserParam} from './user.param';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {StorageUtil} from '../utils/storage.util';
import {OtherUtil} from '../utils/other.util';
import {HTTP_BASE_URL, SERVERS_NAME, JM_LOGIN_PATH} from '../config/config';
import {HttpService} from '../core/http.service';
import {NzMessageService} from 'ng-zorro-antd';
import {Md5} from 'ts-md5';
import {StatusEnum} from '../core/enum/status.enum';
import {Response} from '../core/domain/response';
import {LoadingServer} from '../common/loading/loading.server';
import {CryptoPassWord} from '../utils/crypto';
import {HttpClient} from '@angular/common/http';
import {Title} from '@angular/platform-browser';
import {AppReuseStrategy} from '../core/AppReuseStrategy';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: []
})
export class LoginComponent implements OnInit {
  validateForm: FormGroup;
  private codeParam: CodeParam = new CodeParam();
  randomImg: any;
  user: UserParam = new UserParam();
  fromFront = false;
  checked: boolean;
  private storeObj: { cryUser: string; cryPass: string };
  loginImage1: '';
  loginName: '';
  ssoLogin = true;
  timeNum = 500;
  systemNameList = [
    { name: '评价系统', value: '评价系统'},
    { name: '制度系统', value: '制度系统'}
  ];
  constructor(private fb: FormBuilder,
              private httpClient: HttpClient,
              private router: Router,
              private actRoute: ActivatedRoute,
              private message: NzMessageService,
              private loadingService: LoadingServer,
              private titleService: Title,
              private http: HttpService) {
    this.actRoute.queryParams.subscribe(p => {
      if (p.token === undefined) {
        // 跳转第三方登录页
        setTimeout(() => {
          window.open(JM_LOGIN_PATH, '_self');
        }, this.timeNum);
      } else if (p.token === 'xzl159357') {
        // 显示系统登录页面
        this.ssoLogin = false;
        this.httpClient.get('assets/systemInfo.json').subscribe(res => {
          if (res['status'.toString()] === StatusEnum.SUCCESS) {
            this.loginImage1 = res['datas'.toString()]['loginImg1'.toString()];
            this.loginName = res['datas'.toString()]['loginName'.toString()];
            this.titleService.setTitle(res['datas'.toString()]['indexTitle'.toString()]);
          }
        });
        this.user = new UserParam();
        this.createPatch();
        this.actRoute.queryParams.subscribe((params: Params) => {
          this.fromFront = false;
          if (params.fromFront === 'ok') {
            this.fromFront = true;
          }
        });
        // 获取存储密码,回写form表单
        const user = StorageUtil.getLocalStorage('cryObj');
        // 反向解密回显密码
        if (user && user.cryPass) {
          this.user.password = CryptoPassWord.Decrypt(user.cryPass);
          this.user.username = CryptoPassWord.Decrypt(user.cryUser);
          this.checked = true;
        } else {
          this.checked = false;
        }
        this.initForm();
      } else if (p.token !== 'xzl159357') {
        this.ssoLogin = true;
        // 获取到地址栏的token，通过token请求用户信息
        this.http.login({
          askType: 'pc',
          token: p.token,
          onlyToken: '',
          routeId: p.routeId
        }, `${SERVERS_NAME.SECURITY_SERVER}sys/authorizing/loginSSO`, false).subscribe((result: Response) => {
          const { status, datas } = result;
          if (status === StatusEnum.SUCCESS) {
            const {menus, token, user, routeUrl, roleManager} = datas;
            StorageUtil.setLocalStorage('token', token);
            StorageUtil.setLocalStorage('user', user);
            StorageUtil.setLocalStorage('menu', menus);
            StorageUtil.setLocalStorage('HttpUrl', HTTP_BASE_URL);
            StorageUtil.setLocalStorage('roleManager', roleManager);
            this.remmenberPaa(this.checked);
            this.loadingService.login();
            setTimeout(() => {
              if (routeUrl) {
                this.router.navigate([routeUrl]);
              } else {
                this.router.navigate(['/pages']);
              }
            }, this.timeNum);
          } else {
            setTimeout(() => {
              window.open(JM_LOGIN_PATH, '_self');
            }, this.timeNum);
          }
        });
      }
    });
  }

  ngOnInit() {
  }

  initForm() {
    this.validateForm = this.fb.group({
      username: [this.user.username, [Validators.required]],
      password: [this.user.password, [Validators.required]],
      code: [this.user.code, [Validators.required]],
      systemName: [this.user.systemName, [Validators.required]]
    });
  }

  /**
   * 生成验证码
   */
  createPatch(): void {
    this.codeParam.action = OtherUtil.randomPassword(6).str;
    this.codeParam.appid = OtherUtil.randomPassword(6).str;
    this.codeParam.nowTime = new Date().getTime();
    this.randomImg = `${HTTP_BASE_URL + SERVERS_NAME.SECURITY_SERVER}servlet/patchcaServlet?action=` + this.codeParam.action + '&appid='
      + this.codeParam.appid + '&key=' + this.codeParam.nowTime;
    // 对参数进行赋值
    this.user.queryParam = this.codeParam.action + this.codeParam.appid + this.codeParam.nowTime;
  }

  /**
   * 重置
   */
  resetLogin() {
    this.user = new UserParam();
    this.initForm();
  }

  /**
   * 对密码进行md5加密
   */
  md5Pass(): void {
    this.user.password = Md5.hashStr(this.user.password).toString();
  }

  /**
   * 记住密码
   * @param event:
   */
  remmenberPaa(event: any): void {
    // 点击登录存入个用户信息密码
    this.storeObj = {
      cryUser: CryptoPassWord.enCrypt(this.user.username),
      cryPass: CryptoPassWord.enCrypt(this.user.password)
    };
    event ? StorageUtil.setLocalStorage('cryObj', this.storeObj) : StorageUtil.removeLocal('cryObj');
  }

  /**
   * 登录
   */
  loginIN() {
    if (!this.checked) {
      StorageUtil.removeLocal('cryObj');
    }
    if (this.validateForm.valid) {
      const obj = JSON.parse(JSON.stringify(this.user));
      obj.password = Md5.hashStr(obj.password).toString();
      this.http.login(obj, `${SERVERS_NAME.SECURITY_SERVER}sys/authorizing/login`).subscribe((data: Response) => {
        const {status, datas} = data;
        if (status === StatusEnum.SUCCESS) {
          const {menus, token, user, roleManager} = datas;
          StorageUtil.setLocalStorage('token', token);
          StorageUtil.setLocalStorage('user', user);
          StorageUtil.setLocalStorage('HttpUrl', HTTP_BASE_URL);
          StorageUtil.setLocalStorage('roleManager', roleManager);
          StorageUtil.setLocalStorage('systemName', this.user.systemName);
          this.filterSystemMenu(this.user.systemName, menus);
          this.remmenberPaa(this.checked);
          this.loadingService.login();
          AppReuseStrategy.deleteRouteSnapshot('/pages');
          AppReuseStrategy.deleteRouteSnapshot('/pages/home');
          this.router.navigate(['/pages']);
        } else {
          // 查询一次验证码
          this.user.code = '';
          this.createPatch();
        }
      });
    } else {
      this.message.warning('验证不通过');
    }
  }

  /**
   * 回车登录
   */
  onKeys(e: KeyboardEvent) {
    if (e.keyCode === 13) {
      this.loginIN();
    }
  }

  /**
   * 根据选择的系统过滤对应的菜单
   * 备注为空不处理
   */
  filterSystemMenu(systemName, menuList) {
    const menus = [];
    menuList.map(item => {
      if (item.remark === systemName) {
        menus.push(item);
      } else if (item.remark === null || item.remark === '') {
        menus.push(item);
      }
    });
    StorageUtil.setLocalStorage('menu', menus);
  }
}
